package com.ym.b2b.payment.service.impl;

import javax.annotation.Resource;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.allinpay.ets.client.PaymentResult;
import com.allinpay.ets.client.RequestOrder;
import com.ym.b2b.commons.exception.BaseException;
import com.ym.b2b.commons.service.BaseService;
import com.ym.b2b.order.dao.EmSOrderDao;
import com.ym.b2b.order.sqlbean.EmSOrder;
import com.ym.b2b.order.vo.OrderInfoVO;
import com.ym.b2b.payment.controller.allinPay.AllinParam;
import com.ym.b2b.payment.service.AllinPayService;
import com.ym.b2b.payment.util.PayUtil;
import com.zc.commons.base.Result;

/**
 * @ClassName: AllinPayServiceImpl
 * @Description: TODO
 * @Author tangxj
 * @Date 2015-3-31 下午4:13:43
 * @Modify
 * @CopyRight B2B小组
 */

@Service
public class AllinPayServiceImpl extends BaseService implements AllinPayService {

    @Resource
    private AllinParam  allinParam;
    @Autowired
    private EmSOrderDao orderDao;

    @Override
    public Result payOrder(OrderInfoVO vo) throws BaseException {
        Result ret = new Result();

        try {
            logger.debug("orderCode:" + vo.getOrderCode());
            if (StringUtils.isBlank(vo.getOrderCode())) {
                ret.setCodeResult(Result.CODE_100, "订单号不能为空!");
                return ret;
            }
            // 订单总单
            EmSOrder emSOrder = new EmSOrder();
            emSOrder.setOrderCode(vo.getOrderCode());
            emSOrder = orderDao.searchOrderDetail(emSOrder);

            if (null == emSOrder) {
                ret.setCodeResult(Result.CODE_100, "订单不存在 请确认传入的订单号!");
                return ret;
            }
            String serverUrl = allinParam.getServerUrl();
            allinParam.setOrderNo(emSOrder.getOrderCode());
            // allinParam.setOrderAmount(emSOrder.getConfirmMoney());
            allinParam.setOrderDatetime(emSOrder.getCreateDate().toString());
            // 传入参数
            RequestOrder requestOrder = new RequestOrder();
            String inputCharset = allinParam.getInputCharset();
            if (null != inputCharset && !"".equals(inputCharset)) {
                requestOrder.setInputCharset(Integer.parseInt(inputCharset));
            }
            requestOrder.setPickupUrl(allinParam.getPickupUrl());
            requestOrder.setReceiveUrl(allinParam.getReceiveUrl());
            requestOrder.setVersion(allinParam.getVersion());
            String language = allinParam.getLanguage();
            if (null != language && !"".equals(language)) {
                requestOrder.setLanguage(Integer.parseInt(language));
            }
            requestOrder.setSignType(Integer.parseInt(allinParam.getSignType()));
            requestOrder.setPayType(Integer.parseInt(allinParam.getPayType()));
            requestOrder.setIssuerId(allinParam.getIssuerId());
            requestOrder.setMerchantId(allinParam.getMerchantId());
            requestOrder.setPayerName(allinParam.getPayerName());
            // requestOrder.setPayerEmail("");
            requestOrder.setPayerTelephone(allinParam.getPayerTelephone());
            requestOrder.setPayerIDCard(allinParam.getPayerIDCard());
            requestOrder.setPid(allinParam.getPid());
            requestOrder.setOrderNo(allinParam.getOrderNo());
            requestOrder.setOrderAmount(allinParam.getOrderAmount().longValue() * 1000);
            requestOrder.setOrderCurrency(allinParam.getOrderCurrency());
            requestOrder.setOrderDatetime(allinParam.getOrderDatetime());
            // requestOrder.setOrderExpireDatetime(orderExpireDatetime);
            // requestOrder.setProductName(productName);
            // if(null!=productPrice&&!"".equals(productPrice)){
            // requestOrder.setProductPrice(Long.parseLong(productPrice));
            // }
            // if(null!=productNum&&!"".equals(productNum)){
            // requestOrder.setProductNum(Integer.parseInt(productNum));
            // }
            // requestOrder.setProductId(productId);
            // requestOrder.setProductDesc(productDesc);
            // requestOrder.setExt1(ext1);
            // requestOrder.setExt2(ext2);
            // requestOrder.setExtTL(extTL);//通联商户拓展业务字段，在v2.2.0版本之后才使用到的，用于开通分账等业务
            // requestOrder.setPan(pan);
            requestOrder.setTradeNature(allinParam.getTradeNature());
            requestOrder.setKey(allinParam.getKey()); // key为MD5密钥，密钥是在通联支付网关会员服务网站上设置。

            String strSrcMsg = requestOrder.getSrc(); // 此方法用于debug，测试通过后可注释。
            String strSignMsg = requestOrder.doSign(); // 签名，设为signMsg字段值。

            NameValuePair[] data = { new NameValuePair("requestOrder", JSON.toJSONString(requestOrder)) };
            String returnBody = PayUtil.doHttpPost(serverUrl, data);
            PaymentResult paymentResult = JSON.parseObject(returnBody, PaymentResult.class);
            if ("1".equals(paymentResult.getPayResult())) { // 1.支付成功

            } else {
                ret.setCodeResult(Result.CODE_100, "订单支付异常!");
                return ret;
            }

            ret.putData("emSOrder", emSOrder);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("支付异常：" + e.getMessage());
        }
        return ret;
    }

}
